package com.robot.base.utils

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

object JobUtil {



    fun countDownCoroutines(
        total: Int, onTick: (Int) -> Unit, onFinish: () -> Unit,
        scope: CoroutineScope = GlobalScope
    ): Job {
        return flow {

            for (i in total downTo 0) {
                emit(i)
                delay(1000)
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion { onFinish.invoke() }
            .onEach { onTick.invoke(it) }
            .flowOn(Dispatchers.Main)
            .launchIn(scope)
    }

    fun countUpCoroutines(
        onTick: (Long) -> Unit, onFinish: () -> Unit,
        scope: CoroutineScope = GlobalScope
    ): Job {
        var startTime = 0L
        return flow {
            while (true) {
                emit(startTime)
                delay(5000)
                startTime++
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion { onFinish.invoke() }
            .onEach { onTick.invoke(startTime * 5000) }
            .flowOn(Dispatchers.Main)
            .launchIn(scope)
    }
}